<?php

namespace App\Services\Core\Store\Haodai;

use Prophecy\Exception\Exception;
use App\Helpers\Http\HttpCurl;

/**
*
* 好贷服务
*
*/
class HaodaiService
{

    // 好贷提供渠道id和标识
    protected $channel_id = 34;
    protected $biaoshi    = 19;
    // 加解密密钥
    private static  $hd_secret_key = 'sARkkskBKkHGqFNhme0A4CmvnJZU40ei';
    protected $haodaiUrl           = 'http://oc.haodai.com/Center/pushOrder';


   /**
    * 贷款信息加密方法
    *
    */
    public static function encrypt($input)
    {
        $size  = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $pad   = $size - (strlen($input) % $size);
        $input = $input . str_repeat(chr($pad), $pad);

        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, self::$hd_secret_key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return base64_encode($data);
    }

   /**
    * 贷款信息解密方法
    *
    */    
    public static function decrypt($input)
    {
        if(empty($input)){
            return '';
        }
        $input     = base64_decode($input);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::$hd_secret_key, $input, MCRYPT_MODE_ECB);
        $dec_s   = strlen($decrypted);
        $padding = ord($decrypted[$dec_s - 1]);
        return substr($decrypted, 0, -$padding);
    }

   /**
    * 好贷三方对接请求
    *
    */ 
    public function Send($data)
    {

        // 声明好贷渠道id和标识
        $params = array(
            'channel_id' => $this->channel_id,
            'biaoshi'    => $this->biaoshi
        );
        // 贷款信息进行加密处理
        $params['field'] = $this->encrypt(json_encode($data));
        $params = json_encode($params);
        // 发送请求
        $response = HttpCurl::i()->POST($this->haodaiUrl ,$params ,$contentType = 'application/json;charset=UTF-8');
        // 好贷订单id解密处理
        $response = json_decode($response,true);
        $response['details'] = $this->decrypt($response['details']);
        if(!empty($response['details'])){
            $response['details'] = json_decode($response['details'],true);
        }
        $response = json_encode($response,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        return ($response);
    }


}
